package com.aat.dxfy.netty.test02;

import java.io.UnsupportedEncodingException;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MainServer {

	private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(MainServer.class);

	private void start(int port) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, worker);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.TCP_NODELAY, true);
			bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline p = ch.pipeline();
					p.addLast(new NettyServerHandler());
				}
			});
			//
			ChannelFuture f = bootstrap.bind(port).sync();
			if (f.isSuccess()) {
				log.debug("启动Netty服务成功,端口号：" + port);
			}
			// 关闭连接
			f.channel().closeFuture().sync();

		} catch (Exception e) {
			log.error("启动Netty服务异常,异常信息：" + e.getMessage());
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();

		}
	}

	public static void main(String[] args) {
		new MainServer().start(9999);
	}

}

class NettyServerHandler extends ChannelHandlerAdapter {

	public void channelread(ChannelHandlerContext ctx, Object msg) {
		ByteBuf buf = (ByteBuf) msg;
		String revieved = getMessage(buf);
		System.out.println("server 接收消息：" + revieved);

		//
		try {
			ctx.writeAndFlush(getSendByteBuf("hello 深思!"));
		} catch (Exception e) {

		}
		//
	}

	/*
	 * 从ByteBuf中获取信息 使用UTF-8编码返回
	 */
	private String getMessage(ByteBuf buf) {

		byte[] con = new byte[buf.readableBytes()];
		buf.readBytes(con);
		try {
			return new String(con, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException {

		byte[] req = message.getBytes("UTF-8");
		ByteBuf pingMessage = Unpooled.buffer();
		pingMessage.writeBytes(req);
		return pingMessage;
	}
}
